package com.gitee.wsl.doc.prosemirror.state.command

import com.gitee.wsl.doc.prosemirror.state.Command
import com.gitee.wsl.doc.prosemirror.state.CommandDispatch
import com.gitee.wsl.doc.prosemirror.state.EditorState
import com.gitee.wsl.doc.prosemirror.state.selection.TextSelection
import com.gitee.wsl.ext.base.ifValue
import kotlin.math.max
import kotlin.math.min

class NudgeCursorCmd(
    val dir:Int // -1|0|1
): Command{
    override fun exec(
        state: EditorState,
        dispatch: CommandDispatch?,
    ): Boolean {
        val selection = state.selection
        val to = selection.to
        val from = selection.from

        // compute target position
        val emptySelection = (to == from)
        val currentPos = (dir < 0).ifValue( from , to)
        val increment = emptySelection.ifValue( dir , 0)
        val nodeSize = state.doc.nodeSize
        val targetPos = max(0, min(nodeSize, currentPos + increment))
        dispatch?.invoke(
            state.tr.setSelection(
                TextSelection.create(state.doc, targetPos)
            )
        )
        return true;
    }

    companion object{
        val nudgeCursorForwardCmd: Command = NudgeCursorCmd(+1);
        val  nudgeCursorBackCmd: Command = NudgeCursorCmd(-1);
    }
}

val Command.Companion.nudgeCursorForwardCmd: Command
    get() = NudgeCursorCmd.nudgeCursorForwardCmd

val Command.Companion.nudgeCursorBackCmd: Command
    get() = NudgeCursorCmd.nudgeCursorBackCmd
